package com.ben.multiple.poi.easy;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author BenJin Yin
 * @date 2021/12/9
 */
@Slf4j
public class EasyTest {
    public static void main(String[] args) throws FileNotFoundException {
        String file = "C:\\Users\\eversec\\Downloads\\app_issue_20211209161711.xlsx";
        FileInputStream inputStream = new FileInputStream(file);
        List<AppWarnImport> list = new ArrayList<>();
        Listener listener = new Listener(list);
        log.info("start==================");
        ExcelReaderBuilder read = EasyExcel.read(inputStream, AppWarnImport.class, listener);
        read.doReadAll();

        if (listener.getErrorMsg() != null) {
            log.warn("error, {}", listener.getErrorMsg());
            return;
        }
        log.info("end=============================");
        log.info("list size : {}", list.size());
    }

    public static final String[] DISSUASION_FILE_HEADER = {"预警ID", "预警结果", "是否接到诈骗电话、短信、登入诈骗网址", "劝阻方式", "劝阻金额", "受骗金额", "备注"};

    static class Listener extends AnalysisEventListener<AppWarnImport> {
        List<AppWarnImport> list;
        private volatile boolean hasNext = true;
        private String errorMsg;

        public String getErrorMsg() {
            return errorMsg;
        }

        public Listener(List<AppWarnImport> list) {
            this.list = list;
        }

        @Override
        public void onException(Exception exception, AnalysisContext context) throws Exception {
            log.warn("exception, ", exception);
            errorMsg = exception.getMessage();
        }

        @Override
        public void invoke(AppWarnImport data, AnalysisContext context) {
            list.add(data);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            log.info("doAfterAllAnalysed");
        }

        @Override
        public boolean hasNext(AnalysisContext context) {
            return super.hasNext(context) && hasNext;
        }

        @Override
        public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
            boolean b = headMap.values().containsAll(Arrays.asList(DISSUASION_FILE_HEADER));
            if (!b) {
                hasNext = false;
                throw new RuntimeException("格式错误");
            }
            hasNext = false;
            throw new RuntimeException("格式错误");
        }
    }
}
